<?php
namespace App\Util;

use Illuminate\Support\Facades\Cache;

class Qrcode
{
    /**
     * 创建二维码参数,包含uniqid验证字段
     * @param $_data
     * @return array
     */
    public function createParams($_data)
    {
        $_cache_key = $this->getKey($_data);
        $_data["uniqid"] = md5(sha1(uniqid(microtime(),true)));
        Cache::put($_cache_key,$_data["uniqid"],60);
        return $_data;
    }

    /**
     * 验证参数，验证uniqid
     * @param $_data
     * @return bool
     */
    public function checkParams($_data)
    {
        $_uniqid = $_data["uniqid"];
        unset($_data["uniqid"]);
        $_cache_key = $this->getKey($_data);
        $_cache_uniqid = Cache::get($_cache_key);
        if(!$_cache_uniqid || $_uniqid != $_cache_uniqid) {
            return false;
        } else {
            Cache::forget($_cache_key);
            return true;
        }
    }

    /**
     * 查询二维码是否已失效
     */
    public function testQrcode($_data)
    {
        $_cache_key = $this->getKey($_data);
        if(!Cache::get($_cache_key)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取uniqid缓存键名
     * @param $_data
     * @return string
     */
    private function getKey($_data)
    {
        $_key_arr = array_keys($_data);
        sort($_key_arr,SORT_STRING);
        $_key_str = '';
        foreach($_key_arr as $_v){
            $_key_str .= $_v;
        }
        return md5($_key_str);
    }
}
